package com.aabbc.mongodb.controller;

import com.aabbc.mongodb.document.OrderDocument;
import com.aabbc.mongodb.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * OrderController
 *
 * @author: <a href="mailto:chenfenghai@oristartech.com">chenfenghai</a>
 * @version: 1.0
 * @date: 2019-11-26 14:24
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderRepository orderRepository;

    @GetMapping("/test")
    public String test(){
        return "OrderController.test";
    }

    @GetMapping("/{id}")
    public OrderDocument get(@PathVariable Long id){
        return orderRepository.findById(id).orElse(null);
    }

    @GetMapping("/all")
    public Iterable<OrderDocument> all(){
        return orderRepository.findAll();
    }

    @GetMapping("/page")
    public Page<OrderDocument> page(){
        return orderRepository.findAll(PageRequest.of(0, 2));
    }

    @PostMapping
    public OrderDocument save(@RequestBody OrderDocument order){
        return orderRepository.save(order);
    }

    @PostMapping("/save-all")
    public Iterable<OrderDocument> saveList(@RequestBody List<OrderDocument> list){
        return orderRepository.saveAll(list);
    }

    @PutMapping
    public OrderDocument update(@RequestBody OrderDocument order){
        return orderRepository.save(order);
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Long id){
        orderRepository.deleteById(id);
        return "success";
    }
}
